/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.handler;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.star.framework.excel.handler.settings.WaterMark;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 支持水印<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
public class SheetWaterMarkHandler implements SheetWriteHandler, OrderHandler {
  private final WaterMark setting;

  public SheetWaterMarkHandler(WaterMark setting) {
    this.setting = setting;
  }

  @Override
  public void afterSheetCreate(
      WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    String content = setting.getContent();
    try {
      if (StrUtil.isBlank(content)) {
        return;
      }
      ByteArrayOutputStream watermark = this.createWaterMark();

      SXSSFSheet sxssfSheet = (SXSSFSheet) writeSheetHolder.getSheet();
      // 参照：http://www.kuazhi.com/post/424279.html
      // 类型：XSSFSheet 与 SXSSFSheet 区别
      /**
       * SXSSFSheet 和 XSSFSheet 是 Apache POI 中用于处理 Excel 文件的两种不同类型的 Sheet 实现。
       *
       * <p>XSSFSheet 是基于 DOM 模型的实现，它将整个 Excel 文档加载到内存中，并提供了访问和操作 Excel 表格数据的方法。 它适用于处理较小的 Excel
       * 文件，因为将整个文件加载到内存可能会占用较多的系统资源，尤其是对于大型的 Excel 文件。 XSSFSheet 是 Apache POI 对于 Excel 2007+（即
       * .xlsx 格式）的标准实现。
       *
       * <p>SXSSFSheet 是基于流式操作的实现，它将只保留一部分数据在内存中，并允许以流式方式写入和读取数据。 它适用于处理非常大的 Excel
       * 文件，因为它可以在有限的内存空间下处理大量的数据，而无需将所有数据加载到内存中。 SXSSFSheet 是 Apache POI
       * 提供的一种优化的实现，特别适用于需要处理大型数据集的情况。
       */
      XSSFSheet sheet = (XSSFSheet) ReflectUtil.getFieldValue(sxssfSheet, "_sh");

      XSSFWorkbook workbook = sheet.getWorkbook();
      int watermarkIndex = workbook.addPicture(watermark.toByteArray(), Workbook.PICTURE_TYPE_PNG);
      String relationId =
          sheet
              .addRelation(null, XSSFRelation.IMAGES, workbook.getAllPictures().get(watermarkIndex))
              .getRelationship()
              .getId();
      sheet.getCTWorksheet().addNewPicture().setId(relationId);
    } catch (Exception e) {
      log.error("export excel, add watermark {} error, {}", content, e.getMessage());
    }
  }

  private ByteArrayOutputStream createWaterMark() throws IOException {
    int width = setting.getWidth(), height = setting.getHeight();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // microsoft-yahei 微软雅黑
    Font font = new Font("宋体", Font.PLAIN, setting.getFontSize());
    Graphics2D g2d = image.createGraphics();
    image =
        g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    g2d.dispose();
    g2d = image.createGraphics();
    // 设置字体颜色和透明度，最后一个参数为透明度
    g2d.setColor(new Color(255, 0, 0, 17));
    // 设置字体
    g2d.setStroke(new BasicStroke(1));
    // 设置字体
    g2d.setFont(font);
    // 设置倾斜
    g2d.rotate(-0.3, (double) image.getWidth() / 2, (double) image.getHeight() / 2);
    FontRenderContext context = g2d.getFontRenderContext();
    Rectangle2D bounds = font.getStringBounds(setting.getContent(), context);
    double x = (width - bounds.getWidth()) / 2, y = (height - bounds.getHeight()) / 2;
    double ascent = -bounds.getY(), baseY = y + ascent;
    // 写入水印文字原定高度过小，所以累计写水印，增加高度
    g2d.drawString(setting.getContent(), (int) x, (int) baseY);
    // 设置透明度
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
    // 释放对象
    g2d.dispose();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(image, "png", os);

    return os;
  }

  @Override
  public int order() {
    return this.wrapper(OrderStrategyType.SHEET_WATER_MARK);
  }
}
